import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../view/Login.vue'
import Home from '../view/Home.vue'

// 安装路由
Vue.use(VueRouter);

// 配置导出路由
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children: [
      {
        path: 'chat',
        name: 'Chat',
        component: () => import('../view/Chat.vue')
      },
      {
        path: 'friend',
        name: 'Friend',
        component: () => import('../view/Friend.vue')
      },
      {
        path: 'group',
        name: 'GROUP',
        component: () => import('../view/Group.vue')
      },
      {
        path: 'chatbox/:data',
        name: 'ChatBox',
        component: () => import('../view/test.vue')
      },
      {
        path: 'moments',
        name: 'Moments',
        component: () => import('../view/Moments.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'hash'
})

// 优化路由守卫
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('accessToken')
  const isLoginPage = to.path === '/login'
  
  if (!token && !isLoginPage) {
    next('/login')
  } else if (token && isLoginPage) {
    next('/home/chat')
  } else {
    next()
  }
})

export default router
